package com.seguriapp.cometd;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.java.annotation.Listener;
import org.cometd.java.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seguriapp.util.Channels;

/**
 * Service that broadcast to web client
 * 
 * @author Tania Gonzales(taniadgv@gmail.com)
 */
@Named
@Singleton
@Service("ServerService")
public class ServerService {

  private static Logger LOGGER = LoggerFactory.getLogger(ServerService.class);

  @Inject
  private BayeuxServer bayeuxServer;

  @PostConstruct
  public void init() {
  }

  @Listener(Channels.SERVICE_NEW_ALERT)
  public void sendNewAlertMessage(final ServerSession remote, final ServerMessage.Mutable message) {
    final Map<String, Object> params = message.getDataAsMap();
    LOGGER.info("broadcast service new alert");
    bayeuxServer.getChannel(Channels.BROADCAST_NEW_ALERT).publish(remote, params, null);
  }

  @Listener(Channels.SERVICE_NEW_COMPLAINT)
  public void sendNewComplaintMessage(final ServerSession remote, final ServerMessage.Mutable message) {
    final Map<String, Object> params = message.getDataAsMap();
    LOGGER.info("broadcast service new complaint");
    bayeuxServer.getChannel(Channels.BROADCAST_NEW_COMPLAINT).publish(remote, params, null);
  }

}
